package com.doctor.net;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetUtil {

	public static final int TYPE_NONETWORK=0,TYPE_WIFI=1,TYPE_MOBILE=2;
	
	
	/**
	 * 网络连接是否可用(可用不等于有效)
	 * @param context
	 * @return
	 */
	public static boolean hasNetwork(Context context) {
		NetworkInfo workinfo = getNetworkInfo(context);
		if (workinfo == null || !workinfo.isAvailable() || workinfo.getState()!=NetworkInfo.State.CONNECTED) {
			return false;
		}
		return true;
	}
	
	
	/**
	 * wifi是否已连接上
	 * @param context
	 * @return
	 */
	public static boolean isWifiConnected(Context context){
		return getNetworkType(context)==TYPE_WIFI;
	}
	
	
	/**
	 * 获取连接的网络类型
	 * @param context
	 * @return
	 */
	public static int getNetworkType(Context context){
		int type = TYPE_NONETWORK;
		NetworkInfo workinfo = getNetworkInfo(context);
		if (!(workinfo == null || !workinfo.isAvailable() || workinfo.getState()!=NetworkInfo.State.CONNECTED)) {
			type=workinfo.getType();
			if (type==ConnectivityManager.TYPE_WIFI) {
				//wifi网络
				type=TYPE_WIFI;
			} else if (type==ConnectivityManager.TYPE_MOBILE) {
				//GPRS网络
				type=TYPE_MOBILE;
			}
		} 
		return type;
	}
	
	
	/**
	 * 网络是否有效
	 */
	public static boolean isNetworkValid(){
		try {
			HttpURLConnection conn=(HttpURLConnection) new URL("http://www.baidu.com/").openConnection();
			//只请求头部信息以减少流量耗费
			conn.setRequestMethod("HEAD");
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(3000);
			conn.connect();
			int code=conn.getResponseCode();
			conn.disconnect();
			if (code==200) {
				//连接成功
				return true;
			} else {
				return false;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	
	private static NetworkInfo getNetworkInfo(Context context){
		ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo workinfo = con.getActiveNetworkInfo();
		return workinfo;
	}
	
	
	public static Object post(String decode, RequestParams params) {
		DefaultHttpClient client = new DefaultHttpClient();
//		String url = params.context.getString(R.string.app_host).concat(params.context.getString(params.requestUrl));
		String url=params.requestUrl;
		HttpPost post = new HttpPost(url);
		
//		if(!ECApplication.SSId.equals("")) {
//			headers[10] = new BasicHeader("Cookie", "PHPSESSID="+ECApplication.SSId);
//		}
//		
//		post.setHeaders(headers);
		Object obj = null;
		try {
			if (params.requestMap != null) {
				HashMap<String, String> map = params.requestMap;
				ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
				for (Map.Entry<String, String> entry : map.entrySet()) {	
					BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
					pairList.add(pair);
				}
//				HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
				HttpEntity entity = new UrlEncodedFormEntity(pairList);
				post.setEntity(entity);
			}
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				
//				setCookie(response);
//				String result = EntityUtils.toString(response.getEntity(), "UTF-8");
				String result;
				if (decode != null && decode.length() > 0) {
					result = EntityUtils.toString(response.getEntity(), decode).trim();
				} else {
					result = EntityUtils.toString(response.getEntity()).trim();
				}
				
				if (params.bean == String.class) {
					return result;
				}
//				Log.e("response", result);
				if (result.length()<=15 || !"[".equals(result.substring(12, 13))) {
					return null;
				}
//				try {
//					if (invilidateLogin(result)) {
//						return Status.Login;
//					}
//					obj = params.jsonParser.parseJSON(result);
//				} catch (JSONException e) {
//					Logger.e(TAG, e.getLocalizedMessage(), e);
//				}
				if (result.startsWith("Can")) {
					return null;
				}
				Gson gson=new Gson();
				
				obj=gson.fromJson(result, params.bean);
				return obj;
			}
		} catch (ClientProtocolException e) {
//			Logger.e(TAG, e.getLocalizedMessage(), e);
		} catch (IOException e) {
//			Logger.e(TAG, e.getLocalizedMessage(), e);
		}
 		return null;
	}
	
	
	public static Object get(String decode, RequestParams params) {
		DefaultHttpClient client = new DefaultHttpClient();
//		String url = params.context.getString(R.string.app_host).concat(params.context.getString(params.requestUrl));
		String url=params.requestUrl;
		
//		Log.e("i", "Get " + url);
		HttpGet get = new HttpGet(url);
//		get.setHeaders(headers);
		Object obj = null;
		try {

			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//				setCookie(response);
//				String result = EntityUtils.toString(response.getEntity(),"UTF-8");
				String result;
				if (decode != null && decode.length() > 0) {
					result = EntityUtils.toString(response.getEntity(), decode).trim();
				} else {
					result = EntityUtils.toString(response.getEntity()).trim();
				}
				
				if (params.bean == String.class) {
					return result;
				}
				
				if (result.length()<=15 || !"[".equals(result.substring(12, 13))) {
					return null;
				}
//				Log.e("i", result);
//				try {
//					if (invilidateLogin(result)) {
//						return Status.Login;
//					}
//					obj = params.jsonParser.parseJSON(result);
//					
//				} catch (JSONException e) {
//					Logger.e(TAG, e.getLocalizedMessage(), e);
//				}
				if (result.startsWith("Can")) {
					return null;
				}
//				if (url.equals(URLConfig.FREE_ARTICLE_URL)) {
//					FileHelper.writeDataToFile(result,Environment.getExternalStorageDirectory().getPath()+"/c6.txt");
//					return null;
//				}
				Gson gson=new Gson();
				obj=gson.fromJson(result, params.bean);
				return obj;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static void downFile(String remoteUrl, File imgFile){
		FileOutputStream out = null;
		InputStream is = null;

		try {
			URL url = new URL(remoteUrl);
			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

			imgFile.createNewFile();
			out = new FileOutputStream(imgFile, true);

			is = httpConnection.getInputStream();

			int length = httpConnection.getContentLength();
			
			if (length <= 0) {
				return;
			}

			byte[] buff = new byte[1024];
			int size = 0;
			int readSize = 0;

			while ((size = is.read(buff)) != -1) {
				try {
					out.write(buff, 0, size);
					readSize += size;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
